package cn.net.yugu.doraemon.thread;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @description:
 * @author: wanghongli
 * @create: 2023-03-09 10:52:05
 */
public class YgThreadFactory implements ThreadFactory {
    private static final AtomicLong THREAD_COUNT = new AtomicLong();

    private String threadNamePrefix;
    private ThreadGroup threadGroup;
    private Thread.UncaughtExceptionHandler uncaughtExceptionHandler;

    public YgThreadFactory() {
        this("default");
    }

    public YgThreadFactory(String threadNamePrefix) {
        this(threadNamePrefix, null);
    }

    public YgThreadFactory(String threadNamePrefix, ThreadGroup threadGroup) {
        this(threadNamePrefix, threadGroup, null);
    }

    public YgThreadFactory(String threadNamePrefix, ThreadGroup threadGroup, Thread.UncaughtExceptionHandler uncaughtExceptionHandler) {
        this.threadNamePrefix = threadNamePrefix;
        this.threadGroup = threadGroup;
        this.uncaughtExceptionHandler = uncaughtExceptionHandler;
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(threadGroup, r, genThreadName());
        thread.setUncaughtExceptionHandler(uncaughtExceptionHandler);
        return thread;
    }

    public String genThreadName() {
        return (threadNamePrefix + "-" + THREAD_COUNT.getAndIncrement());
    }
}
